package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.domain.ServiceItemAuditVO;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;

    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        ServiceItem oldServiceItem = serviceItemMapper.selectByPrimaryKey(serviceItem.getId());
        //设置审核状态为原来的状态
        serviceItem.setAuditStatus(oldServiceItem.getAuditStatus());

        //处于上架或者审核中不能编辑
        if (ServiceItem.SALESTATUS_ON.equals(oldServiceItem.getSaleStatus())
                || ServiceItem.AUDITSTATUS_AUDITING.equals(oldServiceItem.getAuditStatus()) ){
            throw new BusinessException("处于上架或者审核中不能编辑");
        }


        //如果是套餐并且是审核完成状态 要初始化
        if (ServiceItem.CARPACKAGE_YES.equals(oldServiceItem.getCarPackage())
                && ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())){
            serviceItem.setAuditStatus(0);
        }

        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    public void updateSaleOff(ServiceItem serviceItem) {
        serviceItem.setSaleStatus(0);
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }
    @Override
    public void updateSaleOn(ServiceItem serviceItem) {
        ServiceItem old = this.get(serviceItem.getId());

        if (ServiceItem.SALESTATUS_ON.equals(old.getSaleStatus())){
            throw new BusinessException("处于上架状态中");

        }else if(ServiceItem.AUDITSTATUS_AUDITING.equals(old.getAuditStatus())){
            throw new BusinessException("处于审核状态中");
        }

        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())
                && ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())){
            serviceItem.setAuditStatus(0);
        }

        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void startAudit(ServiceItemAuditVO vo) {
        //做合理化校验
        //根据id把单项查询出来
         ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(vo.getId());
        // 判断是非套餐抛出异常
        if (ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())) {
            throw new BusinessException("非套餐不能进行审核");
        }
        //判断状态是审核中或者审核通过抛出异常
        if(ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())
                || ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus())) {
            throw new BusinessException("不能重新发起审核");
        }
        //把数据保存到CarPackageAudit对象中
        CarPackageAudit carPackageAudit = new CarPackageAudit();
        carPackageAudit.setServiceItemId(vo.getId());
        carPackageAudit.setServiceItemInfo(serviceItem.getInfo());
        carPackageAudit.setServiceItemPrice(serviceItem.getOriginalPrice());
        carPackageAudit.setAuditorId(vo.getDirector());
        carPackageAudit.setCreateTime(new Date());
        carPackageAudit.setCreator(ShiroUtils.getUser().getUserName());
        carPackageAudit.setInfo(vo.getInfo());
        carPackageAudit.setBpmnInfoId(vo.getBpmnInfoId());
        carPackageAuditService.save(carPackageAudit);
        //启动流程实例，设置实例参数

        Map<String, Object> map = new HashMap<>();
        if(vo.getDirector() != null){
            map.put("director", vo.getDirector().toString());
        }
        if(vo.getFinance() != null){
            map.put("finance", vo.getFinance().toString());
        }

        map.put("discountPrice", serviceItem.getDiscountPrice().longValue());
        //设置流程变量
        //调用api启动流程    在activiti中不支持BigDecimal类型
        BpmnInfo bpmnInfo = bpmnInfoService.get(vo.getBpmnInfoId());
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(
                bpmnInfo.getActProcessKey(),
                carPackageAudit.getId().toString(),
                map
        );
        String id = instance.getId();
        //设置流程id到carPackageAudit
        carPackageAudit.setInstanceId(id);
        carPackageAuditService.update(carPackageAudit);
        // 修改服务单项状态为审核中状态
        serviceItemMapper.changeStatus(vo.getId(),ServiceItem.AUDITSTATUS_AUDITING);

    }


}
